<template>
  <div class="app-container">
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.blurry"
          clearable
          size="small"
          placeholder="输入工程号、主合同号、项目编号和项目名称搜索"
          style="width: 350px;"
          class="filter-item"
          prefix-icon="el-icon-search"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select v-model="query.isCollection" style="width: 140px;" placeholder="收藏" clearable class="filter-item" @change="crud.toQuery">
          <el-option value="true" label="我的收藏" />
        </el-select>
        <el-select v-model="query.useTo" style="width: 140px;" placeholder="用途" clearable class="filter-item" @change="crud.toQuery">
          <el-option v-for="item in useToList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <span v-if="advancedSearch">
          <el-select
            v-model="query.siteId"
            clearable
            size="small"
            placeholder="分站点"
            class="filter-item"
            style="width: 110px"
            @change="crud.toQuery"
          >
            <el-option
              v-for="item in siteList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select v-model="query.startStatus" style="width: 140px;" placeholder="启动状态" clearable class="filter-item">
            <el-option v-for="item in startStatusList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="query.runStatus" style="width: 140px;" placeholder="运行状态" clearable class="filter-item">
            <el-option v-for="item in runStatusList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="query.type" clearable size="small" placeholder="项目类型" style="width: 145px" class="filter-item" @change="crud.toQuery">
            <el-option v-for="item in dict.project_type" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="query.industry" clearable size="small" placeholder="所属行业" style="width: 145px" class="filter-item" @change="crud.toQuery">
            <el-option v-for="item in dict.project_industry" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="query.overallFloorage" clearable size="small" placeholder="总建筑面积" style="width: 185px" class="filter-item" @change="crud.toQuery">
            <el-option v-for="item in overallFloorageList" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="query.designSoftware" clearable size="small" placeholder="设计软件" style="width: 185px" class="filter-item" @change="crud.toQuery">
            <el-option v-for="item in dict.software" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
          <treeselect
            v-model="query.deptId"
            :disable-branch-nodes="true"
            :options="deptAlls"
            :load-options="loadDeptAlls"
            placeholder="主承接"
            class="companySty"
          />
          <treeselect
            v-model="query.constructionUnitId"
            :disable-branch-nodes="true"
            :options="constructionUnits"
            :load-options="loadConstructionUnits"
            placeholder="委托单位"
            class="companySty"
          />
          <wlAddress type="default" :address.sync="query.area1" placeholder="地区" style="width: 606px; display: inline-flex;" class="filter-item" :foreign.sync="foreign" :advanced-search="advancedSearch" />
        </span>
        <rrOperation :crud="crud" />
        <QueryToggle :isadvance="advancedSearch" @click.native="advancedSearch=!advancedSearch;searchButtonName=advancedSearch?'简单搜索':'高级搜索';handleCreate()" />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!--表单组件-->
    <el-dialog
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="860px"
    >
      <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="110px" style="margin: -19px 0px 10px -8px;">
        <el-form-item v-if=" crud.status.add" label="方式">
          <el-radio-group v-model="form.mode" class="text-width2" :disabled="isView()" @change="changeMode">
            <el-radio label="1">与企业OA同步</el-radio>
            <el-radio label="2">自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if=" crud.status.add" label="项目类型" prop="type">
          <el-radio-group v-model="form.type" class="text-width2" :disabled="isView()" @change="changeType">
            <el-radio v-for="item in dict.project_type" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="crud.status.add&&oaShow">
          <el-form-item label="有效期" prop="sjcMonth">
            <el-select
              v-model="form.sjcMonth"
              placeholder="请选择"
              class="text-width2"
              :disabled="isView()"
              @change="changeSjcMonth"
            >
              <el-option
                v-for="item in sjcMonthList"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-button style="float: right;margin-right: 19px;" size="mini" type="primary" :loading="isLoading" icon="el-icon-refresh" @click="hanleIncrement">立即更新</el-button>
          <div style="padding: 16px;margin: -9px 0px 0px 35px;">
            <treeselect v-model="search.deptId" :disable-branch-nodes="true" :options="depts" :load-options="loadDepts" placeholder="主承接" class="companySty" style="width: 140px;margin-bottom: 2px" />
            <el-input v-model.trim="search.contractCode" clearable placeholder="主合同号" style="width: 133px" />
            <el-input v-model.trim="search.code" clearable placeholder="项目编号" style="width: 119px" />
            <el-input v-model.trim="search.name" clearable placeholder="项目名称" style="width: 110px" />
            <el-input v-model.trim="search.constructionCode" clearable placeholder="工程号" style="width: 132px" />
            <el-button size="mini" type="primary" icon="el-icon-search" @click="getsearch" />
            <el-button size="mini" type="plain" icon="el-icon-refresh-left" @click="getreset" />
            <el-table
              ref="filterTable"
              :data="projContractList"
              highlight-current-row
              max-height="400"
              :empty-text="loadInfo"
              @current-change="handleCurrentChange"
            >
              <el-table-column
                prop="deptName"
                label="主承接"
                sortable
                column-key="deptName"
              />
              <el-table-column
                prop="contractCode"
                label="主合同号"
                sortable
                column-key="contractCode"
              />
              <el-table-column
                prop="projCode"
                label="项目编号"
                sortable
                column-key="projCode"
              />
              <el-table-column
                prop="name"
                label="项目名称"
                column-key="name"
              />
              <el-table-column
                prop="constructionCode"
                label="工程号"
                sortable
                column-key="constructionCode"
              /></el-table>
          </div>
        </template>
        <template v-if="(crud.status.add&&!oaShow)||crud.status.edit">
          <el-form-item label="主承接" prop="deptId">
            <treeselect
              ref="deptId"
              v-model="form.deptId"
              :disable-branch-nodes="true"
              :disabled="isView()||crud.status.edit===1"
              :options="depts"
              :load-options="loadDepts"
              class="text-width1"
              :class="crud.form.initId!==null||isView()?'treeColor':''"
              placeholder="请选择"
              @input="hanlePlannerList(form.deptId)"
            />
          </el-form-item>
        </template>
        <template v-if="crud.status.add&&!oaShow">
          <el-form-item label="主合同号" prop="contractCode">
            <el-input v-model="form.contractCode" class="text-width2" :maxlength="100" :disabled="isView()" />
          </el-form-item>
          <el-form-item label="工程号" prop="constructionCode">
            <el-input v-model="form.constructionCode" class="text-width2" :maxlength="100" :disabled="isView()" />
          </el-form-item>
          <el-form-item label="项目编号" prop="projCode">
            <el-input v-model="form.projCode" class="text-width2" :maxlength="100" :disabled="crud.form.initId!==null||isView()" />
          </el-form-item>
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="form.name" class="text-width2" :maxlength="100" :disabled="isView()" />
          </el-form-item>
        </template>
        <el-form-item label="配合公司" prop="assistCompany">
          <treeselect
            ref="assist"
            v-model="assistCompanyIds"
            :disable-branch-nodes="true"
            :multiple="true"
            :options="assistCompanys"
            :load-options="assistLoadDepts"
            class="text-width1"
            :class="crud.form.initId!==null||isView()?'treeColor':''"
            placeholder="请选择"
            @input="hanlePlannerList2(assistCompanyIds)"
          />
        </el-form-item>
        <el-form-item label="项目策划人" class="star">
          <el-col :span="24">
            <div>
              <el-button style="margin-bottom: 10px" icon="el-icon-plus" :disabled="isView()" @click="addAll" />
              <el-tooltip v-if="crud.status.add" effect="dark" :content="form.mode==='1'?'请先选择一条数据！':'请先选择主承接！'" placement="top-start">
                <el-button size="mini" type="text" icon="el-icon-warning" />
              </el-tooltip>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item
          v-for="(personnel, index) in form.formPlanner"
          :key="personnel.key"
          style="display: flex;"
          :label="'人员 ' + (index + 1)"
          :prop="'formPlanner.' + index + '.user_id'"
          :rules="{
            required: true, message: '人员不能为空', trigger: 'blur'
          }"
        >
          <el-select
            v-model="personnel.user_id"
            filterable
            placeholder="请选择人员"
            :disabled="(!personnel.userIdIndex && crud.form.initId != null) || isView()"
            style="width: 300px"
            @change="changePlanner(index)"
          >
            <el-option
              v-for="item in plannerList"
              :key="item.value"
              :value="item.value"
              :label="item.label + '（' + item.username + '-' + item.deptName + '）'"
            />
          </el-select>
          <el-tooltip v-if="personnel.userIdIndex !== 1" effect="dark" :content="personnel.enabled ? '禁用' : '激活'" placement="top-start">
            <el-switch
              v-model="personnel.enabled"
              :width="30"
              :disabled="isView()"
              @change="personnel.enabled===!personnel.enabled"
            />
          </el-tooltip>
          <svg-icon
            v-else
            style="margin-left: 8px;width: 1.8em;height: 1.8em;"
            :disabled="form.formPlanner.length <= 1 || isView()"
            icon-class="delete-circle"
            @click="handleDelete(personnel, index)"
          />
          </el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="isView()" type="button" @click="crud.cancelCU">关闭</el-button>
        <div v-else>
          <el-button @click="crud.cancelCU">取消</el-button>
          <el-button slot="reference" :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </div>
    </el-dialog>
    <el-tabs v-model="query.conditionType" style="margin-bottom: 0;margin-top: -10px;" @tab-click="changeConditionType">
      <el-tab-pane v-for="(item,index) in dict.comprehensive_sorting" :key="index" :label="item.label" :name="item.value" />
    </el-tabs>
    <el-table ref="table" v-loading="crud.loading" stripe highlight-current-row :data="crud.data" height="calc(100vh - 410px)" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
      <el-table-column v-if="checkPer(['admin','projectInit:del','projectInit:edit','project:download'])" type="selection" width="55" :selectable="selectable" />
      <!-- 收藏图标列 -->
      <el-table-column label="收藏" width="80">
        <template slot-scope="scope">
          <svg-icon :icon-class="scope.row.isCollection ? 'adminCollection' : 'grayCollection'" class-name="collection-icon" @click="toggleCollection(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="siteName" label="分站点" />
      <el-table-column :show-overflow-tooltip="true" prop="constructionCode" label="工程号" sortable />
      <el-table-column :show-overflow-tooltip="true" prop="contractCode" label="主合同号" sortable />
      <el-table-column :show-overflow-tooltip="true" prop="projCode" label="项目编号" sortable />
      <el-table-column :show-overflow-tooltip="true" prop="projName" label="项目名称" sortable />
      <el-table-column :show-overflow-tooltip="true" prop="stage" label="项目阶段" sortable>
        <template slot-scope="scope">
          {{ dict.label.stage[scope.row.stage] }}
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="startStatus" label="启动状态">
        <template slot-scope="scope">
          {{ formatStartStatus(scope.row.startStatus,scope.row.updateStatus) }}
          <el-tooltip slot="right" effect="dark" content="已启动子项数/总子项数" placement="top-start"><span>{{ startNumuber(scope.row.projId) }}/{{ (!scope.row.projectSubs)?0:(scope.row.hasOwnProperty('projectSubs')&&scope.row.projectSubs.some(data=> data.subNo === '9999'))?scope.row.projectSubs.length-1:scope.row.projectSubs.length }}</span></el-tooltip>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="runStatus" label="运行状态" sortable>
        <template slot-scope="scope">
          {{ formatRunStatus(scope.row.runStatus) }}
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="plannerName" label="项目策划人" sortable />
      <!--        delFlag可以删-->
      <el-table-column v-if="checkPer(['admin','projectInit:edit','project:detail','projectInit:del','project:export'])" label="操作" width="220px" align="center">
        <template slot-scope="scope">
          <!-- 启动状态(-1:启动失败，0：未启动，1：启动中，2：启动成功)-->
          <!--     是不是不是这个公司  isAuth true可以编辑  false 不可以编辑-->
          <udOperation :data="scope.row" :permission="permission" :disabled-edit="!scope.row.isAuth" :disabled-dle="!scope.row.isAuth||!scope.row.delFlag">
            <el-button slot="left" v-permission="permission.detail" size="mini" type="text" @click="viewProject(scope.row)">
              <svg-icon icon-class="detail" /> 详情
            </el-button>
            <el-button slot="right" v-permission="permission.export" :disabled="scope.row.delFlag" size="mini" type="text" icon="el-icon-upload2" @click="exportHtml(scope.row.indexCode)">
              导出工时
            </el-button>
          </udOperation>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>
<script>
import CRUD, { presenter, header, form, crud } from '@brotherCrud/crud'
import rrOperation from '@brotherCrud/RR.operation'
import crudOperation from '@brotherCrud/CRUD.operation'
import udOperation from '@brotherCrud/UD.operation'
import pagination from '@brotherCrud/Pagination'
import WlAddress from '@/components/address/index.vue'
import Treeselect, { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { setLoading, trimAllTab } from '@/utils'
import { validateFile } from '@/utils/validate'
import { mapGetters } from 'vuex'
import { getDepts, getDeptSuperior, getDeptSuperiorSelf } from '@/api/system/dept'
import crudProject, { projPlannerOption, fetchProjContract, fetchIncrementProjContract } from '@/api/project/projectInit'
import { getSiteList } from '@/api/system/user'
import { uniqueArrObj } from '@/utils/index'
import QueryToggle from '../../components/UiFix/QueryToggle.vue'
import { collectProject, cancelCollectProject } from '@/api/project/project'

const defaultForm = { initId: null, mode: null, type: null, sjcMonth: null, deptId: null, projCode: null, name: null, contractCode: null, constructionCode: null, planner: '', formPlanner: [], assistCompany: null }
export default {
  name: 'Project',
  components: { pagination, crudOperation, rrOperation, udOperation, WlAddress, Treeselect, QueryToggle },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['project_type', 'project_industry', 'software', 'stage', 'comprehensive_sorting'],
  cruds() {
    return CRUD({ title: '项目', url: 'api/project', query: { appModel: 'system', conditionType: '0', useTo: 'prod' }, idField: 'initId', sort: 'proj_id,desc', crudMethod: { ...crudProject }})
  },
  data() {
    this.setLoading = setLoading.bind(this)
    const validateCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error('项目编号不能为空'))
      } else if (!validateFile(value)) {
        callback(new Error('项目编号必须符合文件名命名规则'))
      } else if (value.indexOf('-') !== -1) {
        callback(new Error("项目编号不能含有  ' - '"))
      } else {
        this.form.projCode = trimAllTab(value, 'g')
        callback()
      }
    }
    const validateConstructionCode = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!validateFile(value)) {
        callback(new Error('工程号必须符合文件名命名规则'))
      } else {
        this.form.constructionCode = trimAllTab(value, 'g')
        callback()
      }
    }
    return {
      webUrl: '', // 导出超链接
      isForeign: false, // 国内外flag判断
      foreign: false, // 国内外flag判断
      deptId: null,
      constructionUnitId: null,
      depts: [],
      deptAlls: [],
      constructionUnits: [],
      assistCompanys: [], // 配合公司
      assistCompanyIds: [], // 页面配合公司选中值
      timer: '', // 接受定时器
      time: [], // 启动时间
      pageType: '', // 页面类型
      searchButtonName: '高级搜索',
      advancedSearch: false,
      siteList: [], // 站点列表
      plannerList: [], // 策划人列表
      plannerList1: [], // 主承接策划人列表
      plannerList2: [], // 配合公司策划人列表
      projContractList: [], // 合同数据
      projAllContractList: [], // 所有合同数据
      oaShow: true, // 与OA同步里面内容是否显示
      loadInfo: '', // 加载中显示文字
      isLoading: false, // 按钮加载状态
      // 合同号搜索条件
      search: {
        deptId: null,
        contractCode: '',
        code: '',
        name: '',
        constructionCode: ''
      },
      useToList: [
        { label: '正式项目', value: 'prod' },
        { label: '测试项目', value: 'test' },
        { label: '其他', value: 'other' }
      ],
      startStatusList: [
        { label: '启动失败', value: -1 },
        { label: '未启动', value: 0 },
        { label: '启动中', value: 1 },
        { label: '启动成功', value: 2 }
      ], // 启动状态
      runStatusList: [
        { label: '进行中', value: 1 },
        { label: '暂停', value: 2 },
        { label: '完成', value: 3 },
        { label: '废除', value: 4 }
      ], // 运行状态
      sjcMonthList: [
        { label: '近1月', value: '1' },
        { label: '近2月', value: '2' },
        { label: '近3月', value: '3' },
        { label: '近4月', value: '4' },
        { label: '近5月', value: '5' },
        { label: '近半年', value: '6' },
        { label: '近7月', value: '7' },
        { label: '近8月', value: '8' },
        { label: '近9月', value: '9' },
        { label: '近10月', value: '10' },
        { label: '近11月', value: '11' },
        { label: '近1年', value: '12' }
      ], // 有效期
      overallFloorageList: [
        { label: '0-5万平方米', id: 1, value: [0, 50000] },
        { label: '5-10万平方米', id: 2, value: [50000, 100000] },
        { label: '10-20万平方米', id: 3, value: [100000, 200000] },
        { label: '20-50万平方米', id: 4, value: [200000, 500000] },
        { label: '50万平方米以上', id: 5, value: [500000] }
      ], // 建筑面积
      permission: {
        add: ['admin', 'projectInit:add'],
        edit: ['admin', 'projectInit:edit'],
        del: ['admin', 'projectInit:del'],
        download: ['admin', 'project:download'],
        detail: ['admin', 'project:detail'],
        export: ['admin', 'project:export'] // 下载
      },
      rules: {
        type: [
          { required: true, message: '项目类型不能为空', trigger: 'change' }
        ],
        deptId: [
          { required: true, message: '主承接不能为空', trigger: 'blur' }
        ],
        contractCode: [
          { min: 0, max: 100, message: '长度在 0 到 100 个字符', trigger: 'blur' }
        ],
        constructionCode: [
          { validator: validateConstructionCode, trigger: 'blur' },
          { min: 0, max: 100, message: '长度在 0 到 100 个字符', trigger: 'blur' }
        ],
        projCode: [
          { required: true, validator: validateCode, trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '项目名称不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        planner: [
          { required: true, message: '项目策划人不能为空', trigger: 'change' }
        ]
      },
      queryTypeOptions: [
        { key: 'code', display_name: '项目编号' },
        { key: 'name', display_name: '项目名称' },
        { key: 'type', display_name: '项目类型' },
        { key: 'area', display_name: '地区' },
        { key: 'deptId', display_name: '主承接' },
        { key: 'industry', display_name: '所属行业' },
        { key: 'constructionUnitId', display_name: '委托单位' },
        { key: 'overallFloorage', display_name: ' 项目总建筑面积' },
        { key: 'designSoftware', display_name: '设计软件' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  watch: {
    // 监听地区选择框变化
    'query.area1': {
      handler: function handler() {
        if (this.query.area1) {
          let code = ''
          const area = JSON.parse(this.query.area1)
          if (area.length === 3) {
            if (area[0].code) code = area[0].code
            if (area[1].code) code = area[1].code
            if (area[2].code && area[2].code !== '0') code = area[2].code
          }
          if (area.length === 1) code = area[0].code
          this.query.isForeign = this.foreign
          this.query.area = code
          this.crud.toQuery()
        }
      }
    },
    // 监听主承接选择框变化
    'query.deptId': {
      handler: function handler() {
        this.crud.toQuery()
      }
    },
    // 监听委托单位选择框变化
    'query.constructionUnitId': {
      handler: function handler() {
        this.crud.toQuery()
      }
    },
    // 主承接为空，项目策划人人为空
    'form.deptId': {
      handler: function handler() {
        if (!this.form.deptId) {
          this.emptyPlanner1()
        }
      }
    },
    // 配合公司为空，项目策划人人为空
    'assistCompanyIds': {
      handler(val, oldval) {
        if (val.length < oldval.length) {
          this.emptyPlanner2(val)
        }
      }
    },
    // 项目策划人下拉框去除，select框去除
    'plannerList': {
      handler(newVal) {
        if (this.form.formPlanner && (newVal != null && newVal.length > 0)) {
          let formPlanner = []
          if (this.plannerList.length > 0) {
            formPlanner = this.form.formPlanner.filter(v => this.plannerList.some(val => val.value === v.user_id) || v.hasOwnProperty('userIdIndex') === false)
          } else {
            this.form.formPlanner.forEach((obj) => {
              if (!obj.hasOwnProperty('userIdIndex')) {
                formPlanner.push(obj)
              }
            })
          }
          this.form.formPlanner = formPlanner.length > 0 ? formPlanner : [{
            user_id: null,
            userIdIndex: 1,
            enabled: true
          }]
        }
      }
    },
    'crud.status.title': {
      handler: function(val) {
        if (val === '项目') return Object.keys(this.crud.form).forEach(key => { this.crud.form[key] = null })
        /*
          监听 (title) === (初始化title) 说明是 "关闭弹窗" , 将form对象中所有key置为null
          tips：不用 this.crud.form = defaultForm 是因为整个剔除会丢失响应性（vue2的弊端）
                不用 Vue.set() 是因为它只是V2d的一个补丁，未来的版本不会有这个东西，避免升级困难
          */
      }
    }
  },
  created() {
    // 单位加载
    this.getDeptAlls()
    this.getAssist()
    this.getUnitDepts()// 委托单位
    this.hanleSiteList()
  },
  mounted() {
    this.startNumuber()
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  destroyed() {
    clearInterval(this.timer)
  },
  methods: {
    // 切换排序
    changeConditionType(tab) {
      this.query.conditionType = tab.name
      this.crud.params = { conditionType: tab.name }
      this.crud.toQuery()
    },
    /* 设置当前行是否可选*/
    selectable(row) {
      if (row.delFlag && row.isAuth) {
        return true
      } else {
        return false
      }
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh](crud) {
      // 获取数据前设置好接口地址
      return true
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form, type) {
      this.plannerList = []
      this.plannerList1 = []
      this.plannerList2 = []
      this.pageType = ''
      this.oaShow = true
      this.form.type = '1'
      this.form.mode = '1'
      this.form.sjcMonth = '1'
      if (form.initId) {
        // 查看时
        if (type === 'view') {
          this.pageType = type
        }
        this.form.deptId = form.projDeptId
        if (this.form.deptId) {
          this.getSelfSupDepts(this.form.deptId)
          this.hanlePlannerList(this.form.deptId)
        } else {
          this.getDepts()
        }
        if (form.assistCompany) {
          this.assistCompanyIds = JSON.parse(form.assistCompany)
          this.getSupDepts(form.assistCompany, '2')
        } else {
          this.assistCompanyIds = []
          this.getAssist()
        }
        if (this.assistCompanyIds.length > 0) {
          this.hanlePlannerList2(this.assistCompanyIds)
        }
        return true
      } else {
        this.getDepts()
        this.getAssist()
        this.hanleProjContractList(this.form.type, this.form.sjcMonth)// 获取合同数据列表
      }
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.assistCompanyIds = []
      this.form.formPlanner = [{
        user_id: null,
        userIdIndex: 1,
        enabled: true
      }]
    },
    // 初始化编辑时候
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.assistCompanyIds = []
      if (this.crud.data.length > 0) {
        if (form.planner !== null) {
          const planner1 = JSON.parse(form.planner)
          const planner2 = []
          planner1.forEach(item => {
            if (item.enabled === 0) {
              planner2.push({ enabled: false, user_id: item.user_id })
            }
            if (item.enabled === 1) {
              planner2.push({ enabled: true, user_id: item.user_id })
            }
          })
          this.form.formPlanner = planner2
        }
      }
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (this.assistCompanyIds.length > 0) {
        crud.form.assistCompany = JSON.stringify(this.assistCompanyIds)
      }
      if (crud.form.initId === null && this.form.mode === '1') {
        if (!crud.form.contractCode && !crud.form.deptId && !crud.form.projCode && !crud.form.name && !crud.form.constructionCode) {
          this.$message({
            message: '请选择一条合同数据',
            type: 'warning'
          })
          return false
        }
        if (!crud.form.deptId) {
          this.$message({
            message: '所选数据的主承接为空，请重新选择！',
            type: 'warning'
          })
          return false
        }
        if (!crud.form.projCode) {
          this.$message({
            message: '所选数据的项目编号为空，请重新选择！',
            type: 'warning'
          })
          return false
        }
        if (!crud.form.name) {
          this.$message({
            message: '所选数据的项目名称为空，请重新选择！',
            type: 'warning'
          })
          return false
        }
      }
      if (this.form.formPlanner.length > 0) {
        const newArr = this.form.formPlanner.some((item) => {
          return item.enabled === true
        })
        if (newArr) {
          let disUer = false
          let user_id = ''
          for (let i = 0; i < this.form.formPlanner.length - 1; i++) {
            for (let j = i + 1; j < this.form.formPlanner.length; j++) {
              if (this.form.formPlanner[i].user_id === this.form.formPlanner[j].user_id) {
                disUer = true
                this.plannerList.map(item => {
                  if (item.value === this.form.formPlanner[i].user_id) {
                    user_id = item.label
                  }
                })
                this.crud.notify('人员' + user_id + '存在重复分配，请检查！', CRUD.NOTIFICATION_TYPE.ERROR)
                return false
              }
            }
          }
          if (!disUer) {
            const planner = []
            this.form.formPlanner.forEach(item => {
              if (item.enabled === false) {
                planner.push({ enabled: 0, user_id: item.user_id })
              }
              if (item.enabled === true) {
                planner.push({ enabled: 1, user_id: item.user_id })
              }
            })
            crud.form.planner = JSON.stringify(planner)
          }
        } else {
          this.crud.notify('所有项目策划人都是禁用状态，请检查！', CRUD.NOTIFICATION_TYPE.ERROR)
          return false
        }
      }
    },
    // 点击高级搜索
    handleCreate() {
      this.crud.resetQuery()
    },
    // 是否查看
    isView() {
      if (this.pageType === 'view') {
        return true
      } else {
        return false
      }
    },
    // 格式化启动状态
    formatStartStatus(rowData1, rowData2) {
      let x = null
      if (!form.hasOwnProperty('startStatus') || !(rowData1 === 2)) {
        if (!form.hasOwnProperty('startStatus') || (rowData1 === 0)) {
          x = '未启动'
        }
        if (rowData1 === 2) {
          x = '启动成功'
        }
        if (rowData1 === -1) {
          x = '启动失败'
        }
        if (rowData1 === 1) {
          x = '启动中'
        }
      }
      if (rowData1 === 2) {
        if (rowData2 === 0) {
          x = '未更新'
        }
        if (rowData2 === 2) {
          x = '更新成功'
        }
        if (rowData2 === -1) {
          x = '更新失败'
        }
        if (rowData2 === 1) {
          x = '更新中'
        }
      }
      return x
    },
    // 格式化运行状态
    formatRunStatus(rowData) {
      let x = null
      switch (rowData) {
        case 1:x = '进行中'
          break
        case 2:x = '暂停'
          break
        case 3:x = '完成'
          break
        case 4:x = '废除'
          break
        default:
          x = ''
      }
      return x
    },
    // 查看
    hanleView(initId) {
      this.crud.data.map((item, index) => {
        if (item.initId === initId) {
          this.crud.toView(this.crud.data[index], 'view')
        }
      })
    },
    // 委托单位
    getUnitDepts() {
      // isExterna true外部 false内部
      getDepts({ enabled: true }).then(res => {
        this.constructionUnits = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 主承接 获取所有数据
    getDeptAlls() {
      getDepts({ enabled: true, isExternal: false }).then(res => {
        this.deptAlls = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 主承接
    getDepts() {
      getDepts({ enabled: true, isExternal: false, isDataScope: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 配合公司
    getAssist() {
      getDepts({ enabled: true }).then(res => {
        this.assistCompanys = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 委托单位 配合公司 有外部公司
    getSupDepts(deptId, flag) {
      if (deptId) {
        getDeptSuperior(deptId).then(res => {
          const date = res.content
          this.buildDepts(date)
          if (flag === '1') {
            this.constructionUnits = date
          }
          /* 配合公司*/
          if (flag === '2') {
            let a = []
            if (this.form.assistCompany) {
              a = JSON.parse(this.form.assistCompany)
            }
            if (date) {
              this.assistCompanys = this.constructionUnits
              date.map(member => {
                if (member.children) {
                  member.children.map(item => {
                    a.forEach(item2 => {
                      if (item.id === item2) {
                        item.isDisabled = true
                      }
                    })
                  })
                } else {
                  a.forEach(item2 => {
                    if (member.id === item2) {
                      member.isDisabled = true
                    }
                  })
                }
                this.assistCompanys = date
              })
            }
          }
        })
      }
    },
    // 主承接 无外部公司
    getSelfSupDepts(deptId) {
      if (deptId && deptId !== '[]') {
        getDeptSuperiorSelf(deptId).then(res => {
          const date = res.content
          this.buildDepts(date)
          this.depts = date
        })
      }
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 获取弹窗内部门数据 主承接
    loadDeptAlls({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id, isExternal: false }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 获取弹窗内部门数据 委托单位
    loadConstructionUnits({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 获取弹窗内部门数据 主承接
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id, isExternal: false, isDataScope: true }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 获取弹窗内部门数据 配合公司
    assistLoadDepts({ action, parentNode, callback }) {
      const that = this
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            // 配合公司编辑页新增过的不允许去掉
            if (that.form.assistCompany) {
              let a = []
              a = JSON.parse(that.form.assistCompany)
              if (that.crud.form.initId !== null) {
                a.forEach(item2 => {
                  if (obj.id === item2) {
                    obj.isDisabled = true
                  }
                })
              } else {
                obj.isDisabled = false
              }
            }
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 获取子项启动项目数
    startNumuber(projId) {
      let startNum = 0
      this.crud.data.map(i => {
        if (i.projId && projId === i.projId && i.projectSubs && i.projectSubs.length > 0) {
          i.projectSubs.map(item => {
            if (item.startStatus === 2) {
              startNum++
            }
          })
        }
      })
      return startNum
    },
    // 点击操作列导出
    exportHtml(code) {
      const messageStore = JSON.parse(localStorage.getItem('messageStore'))
      if (this.$store.getters.pageParmas.proj_soft_url && this.$store.getters.pageParmas.proj_soft_url.value) {
        this.webUrl = this.$store.getters.pageParmas.proj_soft_url.value + code
      } else if (messageStore && messageStore.proj_soft_url && messageStore.proj_soft_url.value) {
        this.webUrl = messageStore.proj_soft_url.value + code
      } else {
        this.webUrl = ''
      }
      window.open(this.webUrl, '_blank')
    },
    // 查看项目
    viewProject(row) {
      this.$router.push({
        path: '/project/home'
      })
      this.$store.commit('app/SET_CURRENT_PROJECT', row)
    },
    // 获取站点列表
    hanleSiteList() {
      getSiteList({}).then(data => {
        if (data) {
          this.siteList = data.map(object => {
            return {
              value: object.siteId,
              label: object.name
            }
          })
        }
      })
    },
    // 获取获取策划人列表
    hanlePlannerList(deptId) {
      if (deptId) {
        const params = {
          deptId: deptId,
          initId: this.crud.form.initId
        }
        projPlannerOption(params).then(data => {
          if (data) {
            this.plannerList1 = []
            this.plannerList1 = data.map(object => {
              return {
                value: object.id,
                label: object.nickName,
                username: object.username,
                deptId: object.dept.id,
                deptName: object.dept.name
              }
            })
            this.plannerList = uniqueArrObj(this.plannerList2.concat(this.plannerList1), 'value')
          }
        })
      }
    },
    // 获取获取策划人列表
    hanlePlannerList2(deptId) {
      if (deptId && deptId.length > 0) {
        this.plannerList2 = []
        let params = {}
        deptId.forEach(item => {
          params = {
            deptId: item,
            initId: this.crud.form.initId
          }
          projPlannerOption(params).then(data => {
            if (data) {
              const plannerList2 = data.map(object => {
                return {
                  value: object.id,
                  label: object.nickName,
                  username: object.username,
                  deptId: object.dept.id,
                  deptName: object.dept.name
                }
              })
              this.plannerList2 = uniqueArrObj(plannerList2.concat(this.plannerList2), 'value')
              this.plannerList = uniqueArrObj(this.plannerList1.concat(this.plannerList2), 'value')
            }
          })
        })
      }
    },
    //  清空项目策划人1
    emptyPlanner1() {
      this.plannerList = this.plannerList2
      this.plannerList1 = []
    },
    //  清空项目策划人2
    emptyPlanner2() {
      this.plannerList = this.plannerList1
      this.plannerList2 = []
    },
    // 批量新增
    addAll() {
      let list = {}
      list = {
        user_id: null,
        userIdIndex: 1,
        enabled: true
      }
      this.form.formPlanner.push(list)
    },
    // 删除
    handleDelete(row, index) {
      this.form.formPlanner.splice(index, 1)
    },
    // 切换方式
    changeMode(e) {
      this.form.contractCode = null
      this.form.deptId = null
      this.form.name = null
      this.form.projCode = null
      this.form.constructionCode = null
      // 清除验证
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
      if (e === '1') {
        this.oaShow = true
        this.form.type = '1'
        this.form.sjcMonth = '1'
        this.projContractList = []
        this.hanleProjContractList(this.form.type, this.form.sjcMonth)
      }
      if (e === '2') {
        this.oaShow = false
        this.form.type = null
        this.form.sjcMonth = null
        this.getreset()
      }
    },
    // 切换项目类型
    changeType(e) {
      if (this.form.mode === '1') {
        this.projContractList = []
        this.hanleProjContractList(e, this.form.sjcMonth)
      }
    },
    // 切换有效期
    changeSjcMonth(e) {
      this.projContractList = []
      this.hanleProjContractList(this.form.type, e)
    },
    // 获取合同数据列表
    hanleProjContractList(type, sjcMonth) {
      this.loadInfo = '数据加载中...'
      const params = {
        type: type, // 项目类型
        sjcMonth: sjcMonth // 有效期
      }
      fetchProjContract(params).then(data => {
        this.loadInfo = ''
        if (data.length > 0) {
          data.map(item => {
            if (!item.hasOwnProperty('contractCode')) {
              Object.assign(item, {
                contractCode: ''
              })
            }
            if (!item.hasOwnProperty('constructionCode')) {
              Object.assign(item, {
                constructionCode: ''
              })
            }
            if (!item.hasOwnProperty('name')) {
              Object.assign(item, {
                name: ''
              })
            }
            if (!item.hasOwnProperty('projCode')) {
              Object.assign(item, {
                projCode: ''
              })
            }
            if (!item.hasOwnProperty('deptId')) {
              Object.assign(item, {
                deptId: null
              })
            }
            if (!item.hasOwnProperty('deptName')) {
              Object.assign(item, {
                deptName: ''
              })
            }
          })
          this.projContractList = data
          this.projAllContractList = data
        }
      })
    },
    // 选中单行合同数据
    handleCurrentChange(val) {
      if (val) {
        if (val.contractCode !== '') {
          this.form.contractCode = val.contractCode
        } else {
          this.form.contractCode = null
        }
        if (val.deptId !== null) {
          if (val.deptId !== this.form.deptId) {
            this.emptyPlanner1()
            this.form.deptId = val.deptId
            this.hanlePlannerList(this.form.deptId)
          }
        } else {
          this.form.deptId = null
        }
        if (val.name !== '') {
          this.form.name = val.name
        } else {
          this.form.name = null
        }
        if (val.projCode !== '') {
          this.form.projCode = val.projCode
        } else {
          this.form.projCode = null
        }
        if (val.constructionCode !== '') {
          this.form.constructionCode = val.constructionCode
        } else {
          this.form.constructionCode = null
        }
      }
    },
    getsearch() {
      const tabledata = []
      const vm = this
      this.projAllContractList.forEach(item => {
        if (item.contractCode.indexOf(vm.search.contractCode) > -1 && item.projCode.indexOf(vm.search.code) > -1 && item.name.indexOf(vm.search.name) > -1 && item.constructionCode.indexOf(vm.search.constructionCode) > -1 && (!vm.search.deptId || item.deptId.toString().indexOf(vm.search.deptId) > -1)) {
          tabledata.push(item)
        }
      })
      this.projContractList = tabledata
    },
    getreset() {
      this.search = {
        deptId: null,
        contractCode: '',
        code: '',
        name: '',
        constructionCode: ''
      }
      this.projContractList = this.projAllContractList
    },
    changePlanner() {
      for (let i = 0; i < this.form.formPlanner.length - 1; i++) {
        for (let j = i + 1; j < this.form.formPlanner.length; j++) {
          if (this.form.formPlanner[i].user_id === this.form.formPlanner[j].user_id) {
            this.plannerList.map(item => {
              if (item.value === this.form.formPlanner[i].user_id) {
                let user_id = ''
                user_id = item.label
                this.crud.notify('人员' + user_id + '存在重复分配！', CRUD.NOTIFICATION_TYPE.ERROR)
                this.form.formPlanner[j].enabled = true
                this.form.formPlanner[j].userIdIndex = 1
                this.form.formPlanner[j].user_id = null
              }
            })
            return false
          }
        }
      }
    },
    // 立即更新
    hanleIncrement() {
      this.setLoading(true)
      fetchIncrementProjContract().then(res => {
        this.crud.notify('立即更新成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.setLoading(false)
        this.projContractList = []
        this.hanleProjContractList(this.form.type, this.form.sjcMonth)
      }).catch(() => {
        this.setLoading(false)
      })
    },
    // 收藏
    toggleCollection(row) {
      const params = {
        initId: row.initId
      }
      const apiUrl = row.isCollection ? cancelCollectProject : collectProject
      apiUrl(params).then(data => {
        row.isCollection = !row.isCollection
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.abow_dialog[view-distribute] {
  .el-dialog {
    width: 600px;
    max-height: 90%;
    height: 500px;
  }
}
.text-width1{
  width: 580px;
  &.text-width1-table{
    ::v-deep .el-table__body-wrapper{
      min-height: 180px;
    }
  }

}
.text-width2{
  width: 228px
}
.companySty{
  width: 265px;
  font-size: 14px;
  height: 32px;
  display: inline-block;
  vertical-align: middle;
  margin: 0 3px 10px 0;
}
::v-deep .star>.el-form-item__label:before{
  content: "*";
  color: #ff4949;
  margin-right: 4px;
}
.collection-icon{
  width:15px;
  height: 15px;
  cursor: pointer;
  margin-top: 8px;
}
</style>
